<!-- 公共配置面板 -->
<template>
  <div
    v-loading="isLoading"
    class="config-panel config-panel-common"
  >
    <div
      class="container"
      :class="xvueTheme"
    >
      <!-- 基本信息 -->
      <el-tabs v-model="activeName">
        <el-tab-pane
          v-if="layouts.BaseInfo"
          :label="$demoi18n('panel.tab.baseInfo')"
          name="zero"
        >
          <HelpManual :link="helpManualKey" />
          <!-- xvue注册的组件 -->
          <xvp-base-info
            ref="xVueBaseInfo"
            :is-hide-share-parameter="true"
            :widget-instance-id="widgetInstanceId"
            :is-exist-config="true"
            :is-hide-save-button="true"
          />
        </el-tab-pane>

        <!-- 子组件 -->
        <el-tab-pane
          v-if="config.components"
          :label="$demoi18n('common.config-panel.subcomponents')"
          name="components"
        >
          <div class="child_components">
            <AddChildComponentPopup
              ref="addChildPopup"
              @add-child-component="doAddChildComp"
            />
            <el-tabs
              v-if="config.components.length"
              v-model="curChildCompId"
              class="compTabs"
              type="card"
              :editable="childCompEditable"
              @tab-click="initPanelConfig"
              @tab-remove="removeChildComp"
              @tab-add="addChildComp"
            >
              <el-tab-pane
                v-for="(comp, index) in config.components"
                :key="comp.id"
                :name="comp.id"
              >
                <template #label>
                  <span :title="getChildCompTipName(comp.compKey)">{{ getCompName(comp.name) }}</span>
                </template>
                <component
                  :is="getChildPanelVm(comp.compKey)"
                  ref="childComps"
                  :config="comp.config"
                  :orgConfig="comp.config"
                  :widgetInstanceId="`${widgetInstanceId}_child_${comp.id}`"
                  :isChildComponent="true"
                />
              </el-tab-pane>
            </el-tabs>
            <div v-else class="add_child_comp_btn">
              <el-button type="primary" @click="addChildComp">{{ $demoi18n('common.addSubcomponent') }}</el-button>
            </div>
          </div>
        </el-tab-pane>

        <!-- 属性 -->
        <el-tab-pane
          v-if="layouts.PanelProperty"
          :label="propertyLabel"
          name="first"
        >
          <component
            :is="getLayoutVm('PanelProperty')"
            ref="panel_property"
            :config="config"
            :widget-instance-id="widgetInstanceId"
            :widget="widget"
          />
        </el-tab-pane>

        <!-- 数据 -->
        <el-tab-pane
          v-if="layouts.PanelData"
          :label="$demoi18n('panel.tab.data')"
          name="second"
        >
          <component
            :is="getLayoutVm('PanelData')"
            ref="panel_data"
            :config="config"
            :org-config="orgConfig"
            :widget-instance-id="widgetInstanceId"
            :data-source-type-options="isAurora ? auroraDataSourceTypeOptions : dataSourceTypeOptions"
            :is-aurora="isAurora"
            :dataForm="dataForm"
          />
        </el-tab-pane>

        <!-- 联动 -->
        <el-tab-pane
          v-if="layouts.PanelLinkage"
          :label="$demoi18n('panel.tab.linkage')"
          name="third"
        >
          <PanelLinkage
            ref="panel_linkage"
            :config="config"
            :widget-instance-id="widgetInstanceId"
          />
        </el-tab-pane>

      </el-tabs>
      <div v-if="!isChildComponent" class="save_box">
        <el-button
          type="primary"
          class="saveBtn"
          @click.stop="saveAllData()"
        >{{
          $demoi18n('panel.button.apply')
        }}</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { dataSourceTypeOptions, auroraDataSourceTypeOptions } from '@/common/panel_config';
import configPanelBase from '@/mixin/config-panel-base.js';
import HelpManual from '@/components/common/help-manual/help-manual.vue';
import PanelLinkage from '@/components/panel-linkage-new/panel-linkage';
import AddChildComponentPopup from './add-child-component-popup.vue';
import { cloneDeep } from 'lodash';
import { defineAsyncComponent, markRaw } from 'vue';
import { objHas, $warnConfirm } from '@/utils/util';
import childComponents from './child-components.js';

const Comps = {
  'hover-text': markRaw(defineAsyncComponent(() => import('@/components/hover-text/config/config-panel.vue'))),
};

export default {
  name: 'CommonConfigPanel',
  components: {
    HelpManual,
    PanelLinkage,
    AddChildComponentPopup,
  },
  mixins: [configPanelBase],
  provide() {
    return {
      getParentRefVm: refKey => this.$refs[refKey],
    };
  },
  props: {

    // ------------ 默认属性
    config: { type: Object },
    orgConfig: { type: Object },
    widgetInstanceId: { type: String },
    widget: { type: Object, default: () => ({}) },

    // ------------- 扩展属性
    isChildComponent: { type: Boolean, default: false }, // 是否子组件
    layouts: { // 顶部tab布局
      type: Object,
      default: () => ({
        BaseInfo: true,
        PanelProperty: false, // 如果要显示，要传递vue的组件对象
        PanelData: false, // 如果要显示，要传递vue的组件对象
        PanelLinkage: true,
      }),
    },
    childPanelVms: { type: Object, default: () => ({}) }, // 子组件config-panel.vue
    helpManualKey: { type: String, default: '' },
    childCompEditable: { type: Boolean, default: false }, // 可否添加或删除子组件
  },
  data() {
    const config = cloneDeep(this.config);
    return {
      isLoading: false,
      activeName: window.isLocalEnv ? 'first' : 'zero',
      dataSourceTypeOptions: dataSourceTypeOptions,
      auroraDataSourceTypeOptions,
      isAurora: this.$platformName === 'Aurora',
      curChildCompId: config.components?.[0]?.id || '',
      dataForm: config.config.data,
      compVms: {}, // 组件实例缓存
    };
  },
  computed: {},
  watch: {},
  created() {
    this.activeName = this.getInitActiveName();
  },
  methods: {
    getInitActiveName() {
      const {
        BaseInfo,
        PanelProperty,
        PanelData,
        PanelLinkage: _PanelLinkage,
      } = this.layouts;

      if (BaseInfo && !window.isLocalEnv) {
        return 'zero';
      }
      if (objHas(this.config, 'components')) {
        return 'components';
      }
      if (PanelProperty) {
        return 'first';
      }
      if (PanelData) {
        return 'second';
      }
      if (_PanelLinkage) {
        return 'third';
      }
      return '';
    },
    getCompName(compName) {
      const _compName = this.$demoi18n(compName);
      return _compName;
    },
    getAsyncCompVm(compKey) {
      return Comps[compKey];
    },
    getChildPanelVm(key) {
      let vm;
      if (this.childCompEditable) {
        vm = this.getAsyncCompVm(key);
      } else {
        vm = this.childPanelVms[key];
      }
      return vm;
    },
    getLayoutVm(key) {
      const vm = this.layouts[key];
      return vm;
    },
    removeChildComp(compId) {
      $warnConfirm(this.$demoi18n('common.config-panel.confirmDelChildComp'), this.$demoi18n('popup.title.tips')).then(() => {
        const index = this.config.components.findIndex(n => n.id === compId);
        let { curChildCompId, config: { components } } = this;
        if (curChildCompId === compId) {
          components.forEach((n, i) => {
            if (n.id === compId) {
              const nextComp = components[i + 1] || components[i - 1];
              if (nextComp) {
                curChildCompId = nextComp.id;
              }
            }
          });
        }
        this.curChildCompId = curChildCompId;
        this.config.components.splice(index, 1);

        const { cardLayout } = this.$refs['panel_property'].form;
        if (cardLayout) {
          cardLayout.rows.forEach(r => {
            r.cols.forEach(c => {
              c.comps = c.comps.filter(n => n.id !== compId);
            });
          });
        }
      });
    },
    addChildComp() {
      this.$refs.addChildPopup.openDialog();
    },
    doAddChildComp(childCompItem) {
      this.config.components.push(childCompItem);
      this.curChildCompId = childCompItem.id;
      const { cardLayout } = this.$refs['panel_property'].form;
      if (cardLayout) {
        cardLayout.rows[0].cols[0].comps.push({
          id: childCompItem.id,
          compKey: childCompItem.compKey,
        });
      }
    },
    getChildCompTipName(compKey) {
      const item = childComponents.find(n => n.value === compKey);
      return item?.label || '';
    },
  },
};
</script>
<style lang="less" scoped>
// 配置面板通用样式，主要有明亮风格和蓝黑，样式名需一致
@import '../../common/less/config-panel.less';

.config-panel-common{
  .container{
    .add_child_comp_btn{
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}

</style>
